import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 10000
})

// 请求拦截器，添加token到请求头
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器，处理token过期等情况
api.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response) {
      // 身份验证失败
      if (error.response.status === 401) {
        // 清除本地存储的用户信息
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        
        // 跳转到登录页
        window.location.href = '/login'
      }
    }
    return Promise.reject(error)
  }
)

/**
 * 登录
 * @param {Object} data - 登录信息
 * @returns {Promise} - 登录请求
 */
export function login(data) {
  return api({
    url: '/auth/login',
    method: 'post',
    data
  })
}

/**
 * 验证token
 * @param {String} token - 令牌
 * @returns {Promise} - 验证请求
 */
export function validateToken(token) {
  return api({
    url: '/auth/validate',
    method: 'get',
    params: { token }
  })
}

export default api 